<template>
<div class="source">
    <div class="login-form">
        <div class="avator-box">
                <img src="../../assets/logo.png" alt="path error">
        </div>
    <el-form ref="loginForm"  label-width='80px' :model="loginForm"   :rules='rules' autocomplete='on' class="form-login">
            <div class="title"><span>出库机自助服务系统</span></div>
           <el-form-item label='用户名' prop='username' >
               <el-input type='text' v-model="loginForm.username" autocomplete='on' name='username'>
                   <template #prefix>
                       <i class="el-icon-user el-input__icon"></i>
                   </template>
               </el-input>
           </el-form-item>
            <el-form-item prop='password' label='密码' autocomplete='on'>
                 <el-input type='password' v-model="loginForm.password" autocomplete='off' porp='password' name='password'>
                      <template #prefix>
                       <i class="el-icon-lock el-input__icon"></i>
                   </template>
                 </el-input>
            </el-form-item>
        <el-checkbox v-model="checked" style="margin-left:30px">记住我&nbsp;</el-checkbox>
    <el-tooltip effect="light" content="点击记住我并且登录成功后,下次登录时会自动填充账号密码" placement="top-start">
     <i class="el-icon-question"></i>
    </el-tooltip>
    <el-form-item class="btns" label-width="0px">
        <el-button type='primary' @click="toLogin">登录</el-button>
    </el-form-item>
    </el-form>
    </div>
    </div>
</template>

<script>
import{ mapMutations } from'vuex'
import CryptoJS from 'crypto-js'
export default {
    name:'Login',
        data(){
            return {
            loginForm:{
                username:'',
                password:''
            },
            checked: false,
            rules:{
               username:[
                    {required:true,message:'邮箱不能为空',trigger:'blur'}
               ],
               password:[
                   {required:true,message:'密码不能为空',trigger:'blur'}
               ]
            },
            
            }
        },
        methods:{
            ...mapMutations(['setToken']),
            toRegister(){
                this.$router.push('/register')
            },
            toLogin(){
               this.$http.post('/login',this.loginForm).then((res)=>{
                    if(res.data.meta.status===400)
                    { this.$message({
                        message:'用户名或密码错误',
                        type:'error'
                    })}
                   else{
                         this.$message({
                        message:'登录成功',
                        type:'success'
                        
                    })
                    this.setToken({token:res.data.data.token})
                    this.$router.push('/home')
                    if (this.checked === true) {
                    console.log('checked == true')
                    //  传入账号名，密码，和保存天数3个参数
                    this.setCookie(this.loginForm.username, this.loginForm.password, 7)
                    } else {
                    console.log('清空Cookie')
                    //  清空Cookie
                    this.clearCookie()
                    }
                    console.log('登陆成功')
                            }    
               }).catch(err=>{
                  this.$message({
                      message:'服务器忙,请稍后再试',
                      type:'warning',
                      
                  })
               })                
            },
            reset(){
                this.$refs.loginForm.resetFields()
            },
             setCookie (username, password, exdays) {
      // 使用CryptoJS方法加密
      const pwdpassword = CryptoJS.AES.encrypt(password, 'secret key 123')
      var exdate = new Date() //  获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) //  保存的天数
      // 字符串拼接cookie
      window.document.cookie = 'username' + '=' + username + ';path=/;expires=' + exdate.toGMTString()
      window.document.cookie = 'password' + '=' + pwdpassword + ';path=/;expires=' + exdate.toGMTString()
    },
    //  读取cookie
    getCookie: function () {
      console.log(23)
      console.log(document.cookie)
      if (document.cookie.length > 0) {
        var arr = document.cookie.split('; ') // 这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split('=') // 再次切割
          // 判断查找相对应的值
          if (arr2[0] === 'username') {
            this.loginForm.username = arr2[1] // 保存到保存数据的地方
          } else if (arr2[0] === 'password') {
            // 拿到拿到加密后的密码arr2[1]并解密
            var bytes = CryptoJS.AES.decrypt(arr2[1].toString(), 'secret key 123')
            console.log(bytes)
            // 拿到解密后的密码（登录时输入的密码）
            var plaintext = bytes.toString(CryptoJS.enc.Utf8)
            console.log(plaintext)
            this.loginForm.password = plaintext
          }
        }
      }
    },
    // 清除cookie
    clearCookie: function () {
      this.setCookie('', '', -1) // 修改2值都为空，天数为负1天就好了
    }
        },
     created() {
         this.getCookie()
     }
} 
</script>

<style scoped>
        .login-form{
            position:absolute;
           height: 350px;
            width: 450px;
             left:50%;
             top: 50%;
             border-radius: 20px;
             transform: translate(-50%,-50%);
           background-color:#fff;
            box-sizing: border-box;
        }
        .source{
            height: 100%;
            background-color: #eee;
        }
        .btns{
            display: flex;
            justify-content: space-evenly;
        }
         .login-form:hover{
           box-shadow:0 0 8px 0 rgba(232, 237, 250,0.8),0 2px 4px 0 rgba(232, 237, 250,0.9);
           transition: 0.5;
         }
         .avator-box{
             width: 100px;
             height: 100px;
             border: 1px solid #eee;
             border-radius: 50%;
             box-sizing: border-box;
             padding: 8px;
             position:absolute;
             transform: translate(-50%,-50%);
             left:50%;
              background-color: #eee;
         }
         img{
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background-color: #eee;
         }
         .form-login{
                position: absolute;
                bottom: 20px;
                left: 0;
                right: 0;
                /* box-sizing: border-box; */
                padding: 0 30px 0 10px;
         }
         .title{
                text-align: center;
                letter-spacing: 10px;
                font-size: 26px;
                margin-top: 20px;
                margin-bottom: 20px;
                position: relative;
                right: -16px;
         }
</style>